<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package     CodeIgniter
 * @author      www.ci-guide.info
 * @copyright   Copyright (c) 2006 - 2011, EllisLab, Inc.
 * @license     http://codeigniter.com/user_guide/license.html
 * @link        http://www.ci-guide.info/
 * @since       Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Shopping Cart Class exteded CI_Cart
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Shopping Cart for Japanese
 * @author      http://www.ci-guide.info/
 * @link        http://www.ci-guide.info/practical/library/cart/
 */
class MY_Cart extends CI_Cart {

    //  alpha-numeric, dashes, underscores, colons, periods or Japanese (UTF-8)
    var $product_name_rules = '\.\:\-_ a-z0-9一-龠ぁ-んァ-ヴー';

    public function __construct($params = array())
    {
        parent::__construct($params);
        log_message('debug', 'MY_Cart Class Initialized');
    }

    public function format_number($n = '')
    {
        if ($n == '')
        {
            return '';
        }

        // Remove anything that isn't a number or decimal point.
        $n = trim(preg_replace('/([^0-9\.])/i', '', $n));

        if ($this->CI->config->item('language') == 'japanese') {
            return number_format($n);
        }
        else {
            return number_format($n, 2, '.', ',');
        }
    }
    
    function upsert($cart_data = array()){
    	
		// Was any cart data passed? No? Bah...
		if ( ! is_array($cart_data) OR count($cart_data) == 0)
		{
			log_message('error', 'The insert method must be passed an array containing data.');
	    	return FALSE;
		}
 		log_message ('debug','[upsert] param ' .$cart_data['id'].':'.$cart_data['qty'].':'.$cart_data['price'].':'.$cart_data['name'] );
		    	 
    	$rowid = null;
    	$qty = $cart_data['qty'];
    	//登録か更新か
    	foreach($this->contents() as $items){
    		if($items['id']==$cart_data['id']){
    			$rowid = $items['rowid'];
    			$qty += $items['qty'];
    			break;
    		}
    	}
    		
    	if($rowid == null){
    		$data = array(
    				'id'        	 => $cart_data['id'],
    				'qty'       	 => $cart_data['qty'],
    				'price'     	 => $cart_data['price'],
    				'name'      	 => $cart_data['name']
    		);
    	
    		$this->insert($data);
    		log_message ('debug','[upsert] insert ' .$data['id'].':'.$data['qty'].':'.$data['price'].':'.$data['name'] );
    		
    	}else{
    		$data = array(
    				'rowid'        	 => $rowid,
    				'qty'       	 => $qty
    		);
    	
    		$this->update($data);
    		log_message ('debug','[upsert] update ' .$data['rowid'].':'.$data['qty']);
    	}
    	return 0;
    }

}
// END MY_Cart Class

/* End of file MY_Cart.php */
/* Location: ./application/libraries/MY_Cart.php */
